//
//  UserAccount.swift
//  sinaweibo
//
//  Created by IZEN on 16/3/11.
//  Copyright © 2016年 IZEN. All rights reserved.
//

import UIKit
import AFNetworking

private let userInfoKey = "cn.itcast.account"

class UserAccount: NSObject {
    
    static let shareAccount = UserAccount()
    
    var access_token: String?
    //token生命周期 单位是秒数
    var expires_in: NSTimeInterval = 0 {
        didSet{
           expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
        }
    }
    
    var expires_date:NSDate?
    
    var uid: String?
    var name: String?
    var avatar_large: String?
    //计算型属性
    var userLogin : Bool {
        //空位未登录
        return access_token != nil
    }
    
    override private init() {
        super.init()
        self.loadUserInfo()
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) { }
    
}

extension UserAccount {
        func loadAccessToken(code : String , finished: (isSuccess: Bool) -> ()) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(url, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            guard let dict = result as? [String : AnyObject] else {

                finished(isSuccess: false)
                return
            }
            
            let token = dict["access_token"]
            print(token)
            
            
            self.loadUserInfo(dict, finished: finished)
            
            }) { (_, error) -> Void in
                print("error")
        }
        
    }
    
    private func loadUserInfo(dict : [String : AnyObject] , finished: (isSuccess: Bool) -> ()) {
        
        let token = dict["access_token"] as! String
        
        let uid = dict["uid"] as! String
        
        let url = "https://api.weibo.com/2/users/show.json"
        
        let parameter = ["access_token" : token , "uid" : uid]
        
        let AFN = AFHTTPSessionManager()
        
        AFN.GET(url, parameters: parameter, progress: nil, success: { (_, result) -> Void in
            
            guard var userInfo = result as? [String : AnyObject] else {

                finished(isSuccess: false)
                return
            }
            
            print(userInfo)
            
            
            for (k,v) in dict {
                
                userInfo[k] = v
            }
            
            //        NSUserDefaults.standardUserDefaults().setObject(userInfo, forKey: "cn.itcast.account")
            
            UserAccount.shareAccount.saveUserInfo(userInfo)
            finished(isSuccess: true)
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print("error")
        }
    }

    
    func saveUserInfo(dict : [String : AnyObject]) {
        //字典转模型
        self.setValuesForKeysWithDictionary(dict)
        //保存用户信息 以字典模式
        let userDefault = NSUserDefaults.standardUserDefaults()
        
        //获取对象的字典信息
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        
        //将用户信息保存到沙盒中
        userDefault.setObject(accountDict, forKey: userInfoKey)
        //同步沙盒
        userDefault.synchronize()
        
    }
    
    func loadUserInfo() {
        
        guard let dict = NSUserDefaults.standardUserDefaults().objectForKey(userInfoKey) as? [String : AnyObject] else {
            return
        }
        
        self.setValuesForKeysWithDictionary(dict)
        
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("正常")
            
        }
        else {
            print("用户已过期")
            self.access_token = nil
        }
    }
}
